package spitfire.ksim.network;

/**
 * <p>
 * KNetAddress represents the network address used in {@link KNetwork}.
 * Every host in the network should have a unique network address.
 * {@link KNetwork} uses this address to identify different hosts and transfer data.
 * </p>
 * 
 * <p>
 * Broadcast a packet should use static field BROADCAST_ADDR to specify the 
 * destination. 
 * </p>
 * 
 * @author Adam
 */
public class KNetAddress implements Comparable<KNetAddress>{
	public static final KNetAddress BROADCAST_ADDR = new KNetAddress(-1);
	private static int nextAddr = 0;
	private int addr = 0;

	private KNetAddress(int addr) {
		this.addr = addr;
	}

	public static KNetAddress getNextNetAddr() {
		return new KNetAddress(nextAddr++);
	}
	
	public static void resetID() {
		nextAddr = 0;
	}

	public static KNetAddress getAddr(int addr) {
		return new KNetAddress(addr);
	}

	@Override
	public boolean equals(Object address) {
		if (address instanceof KNetAddress) {
			return addr == ((KNetAddress) address).addr;
		} else {
			return false;
		}
	}

	@Override
	public int hashCode() {
		return addr;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Addr<");
		if (this.equals(BROADCAST_ADDR)) {
			builder.append("BROADCAST");
		} else {
			builder.append(addr);
		}
		builder.append(">");
		return builder.toString();
	}
	
	int toInt() {
		return addr;
	}
	
	static int getAddrToIntMax() {
		return nextAddr;
	}

	@Override
	public int compareTo(KNetAddress o) {
		return addr - o.addr;
	}
}